//
//  RCConversationsViewController.m
//  League
//
//  Created by JinHvung on 2018/2/11.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "RCConversationsViewController.h"
#import "RCConversionTableViewCell.h"
#import "RYMessageViewController.h"
#import "ConversionModel.h"
#import "AlertViewController.h"

@interface RCConversationsViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

/**
 会话数据
 */
@property (nonatomic, strong)NSMutableArray<ConversionModel *> *conversationModels;

@end

static NSString *RCConversionTableViewCellID = @"RCConversionTableViewCell";
@implementation RCConversationsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (UITableView *)tableView {
    if(!_tableView) {
        UITableView *tableView = [[UITableView alloc] init];
        tableView.frame = self.tabFrame;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView alloc];
//        tableView.backgroundColor = RANDOM_COLOR;
        [tableView registerNib:[UINib nibWithNibName:RCConversionTableViewCellID bundle:nil] forCellReuseIdentifier:RCConversionTableViewCellID];
        [tableView setSeparatorInset:UIEdgeInsetsZero];
        
        _tableView = tableView;
    }
    
    return _tableView;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.conversationModels.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConversionModel *model = self.conversationModels[indexPath.row];
    
    RCConversionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RCConversionTableViewCellID forIndexPath:indexPath];
    if(!cell) {
        cell = [[RCConversionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RCConversionTableViewCellID];
    }
    
    //headImageView
    cell.headImageView.tag = indexPath.row;
    cell.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headImageViewClick:)];
    [cell.headImageView addGestureRecognizer:headerTap];
    
    //rematchButton
    cell.rematchButton.tag = indexPath.row;
    [cell.rematchButton addTarget:self action:@selector(rematchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //dotLable
    cell.dotLable.hidden = model.conversation && model.conversation.unreadMessageCount ? NO : YES;
    
    //填充数据
    //match
    if(self.index == 0){
        cell.rematchButton.hidden = YES;
        cell.messageLable.hidden = !cell.rematchButton.hidden;
    }
    //expired
    else if(self.index == 1){
        cell.rematchButton.hidden = NO;
        cell.messageLable.hidden = !cell.rematchButton.hidden;
        NSString *buttonStr;
        if(model.matchStatus == 2 || model.matchStatus == 5){
            buttonStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Rematch" : @"叙叙旧";
        }
        else if(model.matchStatus == 3){
            buttonStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Pending" : @"待确认";
        }
        else{
            cell.rematchButton.hidden = YES;
            cell.messageLable.hidden = !cell.rematchButton.hidden;
        }
        [cell.rematchButton setTitle:buttonStr forState:UIControlStateNormal];
    }
    //friends
    else if(self.index == 2){
        cell.rematchButton.hidden = NO;
        cell.messageLable.hidden = !cell.rematchButton.hidden;
        NSString *buttonStr;
        if(model.matchStatus == 3){
            buttonStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Agree ?" : @"同意 ?";
        }
        else if(model.matchStatus == 1){
            buttonStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Pending" : @"待确认";
        }
        else {
            cell.rematchButton.hidden = YES;
            cell.messageLable.hidden = !cell.rematchButton.hidden;
        }
        [cell.rematchButton setTitle:buttonStr forState:UIControlStateNormal];
    }
    //events groups
    else {
        cell.rematchButton.hidden = YES;
        cell.messageLable.hidden = !cell.rematchButton.hidden;
    }
    
    //headImageView
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:model.photoUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    //nickLable timeLable
    cell.nickLable.text = model.name;
    if(self.index <= 2){
        cell.timeLable.hidden = NO;
        NSString *timeStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"days ago" : @"天以前";
        cell.timeLable.text = [NSString stringWithFormat:@"%@ %@", model.days, timeStr];
    }
    else {
        cell.timeLable.hidden = YES;
        CGRect nickFrame = cell.nickLable.frame;
        nickFrame.size.width += cell.timeLable.width;
        cell.nickLable.frame = nickFrame;
    }
    //userInfoLable schoolLable
    NSString *infoStr = @"";
    NSString *schoolStr = @"";
    NSString *MembersStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Members" : @"成员";
    NSString *FriendsStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Friends" : @"好友";
    NSString *MatchsInGroupStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"MatchsInGroup" : @"相配";
    if(self.index <= 2){
        infoStr = [NSString stringWithFormat:@"%ld·%@·%ld", model.age, model.location, model.height];
        schoolStr = model.education;
    }
    else if(self.index == 3){
        infoStr = model.joinedTime;
        schoolStr = [NSString stringWithFormat:@"%@ %@", model.memberCount, MembersStr];
    }
    else{
        infoStr = model.about;
        schoolStr = [NSString stringWithFormat:@"%@ %@·%@ %@·%@ %@", model.size, MembersStr, model.friendCount, FriendsStr, model.matchesInGroupCount, MatchsInGroupStr];
    }
    cell.userInfoLable.text = infoStr;
    cell.schoolLable.text = schoolStr;
    //messageLable
    if(cell.messageLable.hidden){
        return cell;
    }
    NSString *message = @"";
    if(model.conversation){
        if ([model.conversation.lastestMessage isKindOfClass:[RCTextMessage class]]) {
            RCTextMessage *textMsg = (RCTextMessage *)model.conversation.lastestMessage;
            message = textMsg.content;
        } else if ([model.conversation.lastestMessage isKindOfClass:[RCImageMessage class]]) {
            message = @"[图片]";
        } else if ([model.conversation.lastestMessage isKindOfClass:[RCVoiceMessage class]]) {
            message = @"[语音]";
            
        } else if ([model.conversation.lastestMessage isKindOfClass:[RCLocationMessage class]]) {
            message = @"[位置]";
            
        } else if ([model.conversation.lastestMessage isKindOfClass:[RCDiscussionNotificationMessage class]]) {
            message = @"[通知]";
        } else {
            message = @"[其他消息]";
        }
    }
    cell.messageLable.text = message;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    ConversionModel *model = self.conversationModels[indexPath.row];
    if(self.index == 2 && model.matchStatus != 2){
        //不可进入聊天
        return;
    }
    RYMessageViewController *VC;
    //单聊
    if(self.index <= 2){
        VC = [[RYMessageViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId: model.pk];
    }
    else{
        VC = [[RYMessageViewController alloc] initWithConversationType:ConversationType_GROUP targetId: model.rongyun_id];
    }
    VC.model = model;
    VC.index = self.index;
    [self.navigationController pushViewController:VC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - click
- (void)headImageViewClick:(UIGestureRecognizer *)gesture {
    NSInteger index = gesture.view.tag;
    ConversionModel *model = self.conversationModels[index];
    if(self.index <= 2){
        UserProfileViewController *VC = [[UserProfileViewController alloc] init];
        VC.memberId = model.pk;
        VC.isMemberList = YES;
        [self.navigationController pushViewController:VC animated:YES];
    }
    else {
        FirstViewController *VC = [[FirstViewController alloc] init];
        VC.title = model.name;
        VC.state = self.index == 3 ? EventDetailState : GroupDetailState;
        VC._id = model.pk;
        [self.navigationController pushViewController:VC animated:YES];
    }
}

- (void)rematchButtonClick:(UIButton *)sender {
    NSInteger index = sender.tag;
    ConversionModel *model = self.conversationModels[index];
    
    NSString *operate;
    //expired
    //叙叙旧
    if(self.index == 1 && model.matchStatus == 2){
        operate = @"5";
    }
    //叙叙旧
    else if(self.index == 1 && model.matchStatus == 5){
        operate = @"5";
    }
    //friends
    //是否同意
    else if(self.index == 2 && model.matchStatus == 3){
        operate = @"7";
    }
    else{
        return;
    }
    
    
    if([operate isEqual:@"5"]){
        AlertViewController *VC = [[AlertViewController alloc] init];
        [self presentViewController:VC animated:YES completion:nil];
        VC.block = ^(BOOL isConfirm) {
            if(isConfirm){
                [self updateRematchStatus:model operate:operate];
            }
        };
    }
    else{
        [self updateRematchStatus:model operate:operate];
    }
}
- (void)updateRematchStatus:(ConversionModel *)model operate:(NSString *)operate {
    NSDictionary *dic = @{
                          @"requestCustomerId": [UserInfomation shareManager].pk,
                          @"targetCustomerId": model.pk,
                          @"operate": operate
                          };
    NSString *apiStr = @"/match/operate";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", kFirstUrl, apiStr];
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        
        NSLog(@"%@-backDic:%@", apiStr, backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            [self loadData];
        } else {
            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@-backErrorStr:%@", apiStr, backErrorStr);
        
    }];
}

#pragma mark - loadData
- (void)loadData {
    
    NSDictionary *dic = @{
                          @"pk": [UserInfomation shareManager].pk ? [UserInfomation shareManager].pk : @""
                          };
    NSString *apiStr = @"";
    switch (self.index) {
        case 0:
            apiStr = @"/chat/matches";
            break;
            
        case 1:
            apiStr = @"/chat/expired";
            break;
            
        case 2:
            apiStr = @"/chat/friends";
            break;
            
        case 3:
            apiStr = @"/chat/events";
            break;
            
        case 4:
            apiStr = @"/chat/groups";
            break;
        default:
            
            return;
            break;
    }
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", kFirstUrl, apiStr];
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        
        NSLog(@"%@-backDic:%@", apiStr, backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            if(!backDic[@"obj"] || [backDic[@"obj"] isEqual:[NSNull null]]){
                [self.conversationModels removeAllObjects];
                [self.tableView reloadData];
                return;
            }
            NSDictionary *obj = backDic[@"obj"];
            NSArray *datas = nil;
            if(self.index == 3){
                datas = [obj objectForKey:@"events"];
            }
            else if(self.index == 4){
                datas = [obj objectForKey:@"groups"];
            }
            else{
                datas = [obj objectForKey:@"customers"];
            }
            if(datas && datas.count && ![datas isEqual:[NSNull null]]){
                self.conversationModels = [ConversionModel arrayOfModelsFromDictionaries:datas error:nil];
                [self loadConversations];
            }
        } else {
            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        NSLog(@"%@-backErrorStr:%@", apiStr, backErrorStr);
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
    }];
}

- (void)loadConversations {
//    for(ConversionModel *model in self.conversationModels){
//        if(self.index <= 2){
//            model.conversation = [[RCIMClient sharedRCIMClient] getConversation:ConversationType_PRIVATE targetId:model.pk];
//        }
//        else {
//            model.conversation = [[RCIMClient sharedRCIMClient] getConversation:ConversationType_GROUP targetId:model.rongyun_id];
//        }
//    }
//    [self.tableView reloadData];
//    return;
    
    //将会话排序-本地已有会话排前面
    //取本地已存在会话
    NSMutableArray *models = [NSMutableArray array];
//    NSArray *conversations = [[RCIMClient sharedRCIMClient] getConversationList:@[@(1), @(2), @(3), @(4), @(5), @(6), @(7), @(8), @(9)]];
    NSArray *conversations;
    if(self.index <= 2){
        conversations = [[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]];
    }
    else {
        conversations = [[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_GROUP)]];
    }
    //取本地已有会话
    for (RCConversation *conversation in conversations) {
        for (ConversionModel *model in self.conversationModels) {
            if([conversation.targetId isEqual:model.pk]){
                model.conversation = conversation;
                [models addObject:model];
                break;
            }
        }
    }
    //取本地没有会话
    for(ConversionModel *model in self.conversationModels){
        if([models containsObject:model]){
            continue;
        }
        if(self.index <= 2){
            model.conversation = [[RCIMClient sharedRCIMClient] getConversation:ConversationType_PRIVATE targetId:model.pk];
            [models addObject:model];
        }
        else {
            model.conversation = [[RCIMClient sharedRCIMClient] getConversation:ConversationType_GROUP targetId:model.rongyun_id];
            [models addObject:model];
        }
    }
    self.conversationModels = models;
    
    [self.tableView reloadData];
}

@end
